//
//  StoreAddViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/7.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CoreLocation
class StoreAddViewController: BaseViewController {

    @IBOutlet var storeDetailsTableview: UITableView!
    var footerView: StoreDetailsFooterView?
    var showImageIndex : Int?
    var chooseImageType : Int? //0 封面图片 1 展示图片
    
    var storeModel :StoreModel?
    var storeTypeModels:[StoreTypeModel]?
    var tagRunnerImageUrl = ""
    var storeTypeId  = ""
    var isInstallId = "1"
    var lonStr = ""
    var latStr = ""
    
    var provinceIdStr = ""
    var cityIdStr = ""
    var townIdStr = ""
    
    var provinceNameStr = ""
    var cityNameStr = ""
    var townNameStr = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestGetStoreType()
        configView()
        baseSetNavRightButtonWithTitle("添加")
    }
    
    override func baseNavRightButtonPressed(_ button: UIButton) {
        print("保存")
        if footerView?.storeNameTF.text! == "" || self.storeTypeId == "" || self.provinceIdStr == "" || self.cityIdStr == "" || self.townIdStr == "" || footerView?.storeDetailsAddressTF.text! == "" || footerView?.phoneTF.text! == ""{
            MBProgressHUD.alertShow(in: self.view, message: "请填写完整再添加", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            
            return
        }
        var Ids = [String]()
        for (photo) in (self.footerView?.imageArray)! {
            Ids.append(photo.id)
        }
        let photoStr = Ids.joined(separator:",")
        SVProgressHUD.show()
        requestAddStoreInfo(storeName:(footerView?.storeNameTF.text!)!, storeImageUrl:self.tagRunnerImageUrl, storeAddress:(footerView?.storeDetailsAddressTF.text!)!, phone:(footerView?.phoneTF.text!)!, isInstall: self.isInstallId, description:(footerView?.introductionTF.text!)!, content: (footerView?.detailsTF.text!)!, photos:photoStr, storeType:self.storeTypeId)
    }
    
    func configView() -> Void {
        storeDetailsTableview.delegate = self
        storeDetailsTableview.dataSource = self
        storeDetailsTableview.separatorStyle = .none
        storeDetailsTableview.showsVerticalScrollIndicator = false
        footerView = StoreDetailsFooterView.getStoreDetailsFooterView()
        footerView?.storeDetailsAddressTF.delegate = self
        footerView?.tagRunnerBtn.addTarget(self, action: #selector(tagRunerEvents), for: .touchUpInside)
        footerView?.storeTypeBtn.addTarget(self, action: #selector(storeTypeBtnEvents), for: .touchUpInside)
        footerView?.chooseStoreAddressBtn.addTarget(self, action: #selector(storeAddressBtnEvents), for: .touchUpInside)
        
        footerView?.chooseLocationBtn.addTarget(self, action: #selector(chooseLocationBtnEvents), for: .touchUpInside)
        
        footerView?.isInstallPointBtn.addTarget(self, action: #selector(isInstallPointBtnEvents), for: .touchUpInside)
        
        footerView?.callBackBlock({ (index) in
            print(index)
            self.showImageIndex = index
            self.chooseImageType = 1
            self.alertChooseTakePhotoOrAlbum(typeName: "展示图片")
        })
        footerView?.collectionviewHeight.constant = ScaleHeight(200);
        storeDetailsTableview.tableFooterView = footerView
    }
    
    @objc func tagRunerEvents() -> Void {//上传封面图片
        self.chooseImageType = 0
        alertChooseTakePhotoOrAlbum(typeName: "店铺封面图片")
    }
    
    @objc func storeTypeBtnEvents() -> Void {//门店类型
        var Ids = [String]()
        var titles = [String]()
        for (storeType) in storeTypeModels! {
            
            titles.append(storeType.title)
            Ids.append(storeType.id)
        }
        self.view.endEditing(true)
        BRStringPickerView.showStringPicker(withTitle: "门店类型", dataSource: titles, defaultSelValue: titles[0], isAutoSelect: true) { (str,index) in
            
            self.storeTypeId = Ids[index]
            self.footerView?.storeTypeBtn.setTitle(str as? String, for: .normal)
        }
    }
    
    @objc func storeAddressBtnEvents() -> Void {//选择门店地址
        //解析数据
        let path = Bundle.main.path(forResource: "ldlcitylist", ofType: "plist")
        let dic = NSDictionary(contentsOfFile: path!)
        let baseCitymodel = CityDataModel.deserialize(from:dic)!
        let provinces = baseCitymodel.citylist
        var citys = [AddressModel]()
        var towns = [AddressModel]()
//        for provinceModel in provinces! {
//            for son in provinceModel.son! {
//                citys.append(son)
//            }
//        }
//        for cityModel in citys {
//            for son in cityModel.son! {
//                towns.append(son)
//            }
//        }
        let pmodel = provinces![0]
        citys = pmodel.son!
        let cmodel = citys[0]
        towns = cmodel.son!
        //弹出框
        let popPickerView = PopPickerView.getPopPickerView()
        popPickerView.provinces = provinces!
        popPickerView.citys = citys
        popPickerView.towns = towns
        popPickerView.callBackBlock { (pId,cId,tId)  in
            if pId == "cancle" || cId == "cancle" || tId == "cancle" {
            }else {
                self.provinceIdStr = pId
                self.cityIdStr = cId
                self.townIdStr = tId
            }
            bgWindow?.hidBackgroundWindow()
        }
        popPickerView.callNameBackBlock { (provinceName,cityName,townName) in
            self.provinceNameStr = provinceName
            self.cityNameStr = cityName
            self.townNameStr = townName
            self.footerView?.chooseStoreAddressBtn.setTitle(self.provinceNameStr + self.cityNameStr + self.townNameStr, for: .normal)
            bgWindow?.hidBackgroundWindow()
        }
        bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
        bgWindow?.shake(toShow: popPickerView)
    }
    
    @objc func isInstallPointBtnEvents() -> Void {//是否为安装点
        self.view.endEditing(true)
        BRStringPickerView.showStringPicker(withTitle: "是否为安装点", dataSource: ["是","否"], defaultSelValue: "是", isAutoSelect: true) { (str,index) in
            
            self.isInstallId = "\(index + 1)"
            self.footerView?.isInstallPointBtn.setTitle(str as? String, for: .normal)
        }
    }
    
    @objc func chooseLocationBtnEvents() -> Void {//选择店铺定位地址
        let chooseLocationVC = ChooseLocationViewController()
        chooseLocationVC.chooseLoction = self;
    self.navigationController?.pushViewController(chooseLocationVC, animated: true)
    }
    
    //选择照片或者拍照
    func alertChooseTakePhotoOrAlbum(typeName:String) -> Void {
        let alertController = UIAlertController(title: "上传图片", message: typeName,
                                                preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let takephtotAction = UIAlertAction(title: "拍照", style: .default, handler:{
            action in
            let imagePicker = LDImagePicker.sharedInstance()
            imagePicker?.delegate = self as LDImagePickerDelegate
            imagePicker?.show(with: ImagePickerCamera, in: self, scale: 1)
        })
        let albumAction = UIAlertAction(title: "相册", style: .default, handler:{
            action in
            let imagePicker = LDImagePicker.sharedInstance()
            imagePicker?.delegate = self as LDImagePickerDelegate
            imagePicker?.show(with: ImagePickerPhoto, in: self, scale: 1)
            
        })
        alertController.addAction(cancelAction)
        alertController.addAction(takephtotAction)
        alertController.addAction(albumAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    //更新footerView
    func updateFooterView() -> Void {
        if ((storeModel) != nil) {
            
            //赋值
            tagRunnerImageUrl = (storeModel?.thumb)!
            isInstallId = (storeModel?.hide)!
            
            
            //更新UI
            footerView?.TagRunnerImageView.sd_setImage(with: NSURL(string:(storeModel?.thumb)!)! as URL, placeholderImage: UIImage.init(named: "addImage"))
            
            footerView?.introductionTF.text = storeModel?.content
            footerView?.detailsTF.text = storeModel?.description
            footerView?.storeNameTF.text = storeModel?.name
            footerView?.chooseStoreAddressBtn.setTitle((storeModel?.province)! + (storeModel?.city)! + (storeModel?.area)!, for: .normal)
            footerView?.storeTypeBtn.setTitle(storeModel?.jointitle, for: .normal)
            footerView?.storeDetailsAddressTF.text = storeModel?.address
            footerView?.phoneTF.text = storeModel?.phone
            footerView?.imageArray = (storeModel?.acces)!
            
            if (footerView?.imageArray.count)! > 3 {
                footerView?.collectionviewHeight.constant = ScaleHeight(200);
            };
            footerView?.addImageCollectionview.reloadData()
        }
    }
    
//    //根据地名获取经纬度
//    func getLonAndLat(address:String) -> Void {
//        let geoCoder = CLGeocoder()
//        geoCoder.geocodeAddressString(address) { (pls: [CLPlacemark]?, error: Error?)  in
//            if error == nil {
//                print("地理编码成功")
//                guard let plsResult = pls else {return}
//                let firstPL = plsResult.first
//                self.storeModel?.address = (firstPL?.name)!
//                self.latStr = "\((firstPL?.location?.coordinate.latitude)!)"
//                self.lonStr = "\((firstPL?.location?.coordinate.longitude)!)"
//            }else {
//                print("错误")
//            }
//        }
//    }
    
    
    //网络请求
    
    
    //上传单张封面图片
    func requestUploadCoverPhoto(imageName:String,imageData:Data) -> Void {
        //imageType 0 封面图片 1 展示图片....
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData, withName: "file", fileName:imageName, mimeType: "image/jpeg")
        }, to: uploadQiuPhotoUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
                    switch response.result.isSuccess {
                    case true:
                        var basemodel = BaseResponseOfModel<PhotoModel>()
                        basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                        switch basemodel.status! {
                        case true:
                            self.tagRunnerImageUrl = (basemodel.data?.thumb)!
                            print("上传成功")
                        case false:
                            print("数据错误")
                        }
                    case false:
                        print(response.result.error!)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    //上传多张展示图片
    func requestUploadCoverPhotos(imageName:String,imageData:Data) -> Void {
        //        0 1 2 3 4  展示图片....
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData, withName: "files", fileName:imageName, mimeType: "image/jpeg")
        }, to: uploadQiuPhotosUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
                    switch response.result.isSuccess {
                    case true:
                        var basemodel = BaseResponseOfModel<PhotoModel>()
                        basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                        switch basemodel.status! {
                        case true:
                            if (self.footerView?.imageArray.count)! > 0 {
                                if(self.footerView?.imageArray.count)! == self.showImageIndex! {
                                    print("点击的最后一个")
                                    if self.footerView?.imageArray.count != 5{//添加
                                        self.addImageArrayEvents(model: basemodel.data!)
                                    }else {//由于是最后一个 替换
                                        self.replaceImageArrayEvents(model: basemodel.data!)
                                    }
                                }else {//替换
                                    print("其他的")
                                    self.replaceImageArrayEvents(model: basemodel.data!)
                                }
                            } else {//第一个+
                                //添加到图片数组里面
                                self.addImageArrayEvents(model:basemodel.data!)
                                
                            }
                            print("上传成功")
                        case false:
                            print("数据错误")
                        }
                    case false:
                        print(response.result.error!)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    //处理图片数组
    //替换
    func replaceImageArrayEvents(model:PhotoModel) -> Void {
        let photomodel = self.footerView?.imageArray[self.showImageIndex!]
        photomodel?.id = model.id
        photomodel?.url = HeadUrl + model.thumb
        self.footerView?.addImageCollectionview.reloadData()
    }
    //增加
    func addImageArrayEvents(model:PhotoModel) -> Void {
        model.url = HeadUrl + model.thumb
        self.footerView?.imageArray.append(model)
        self.footerView?.addImageCollectionview.reloadData()
    }
    
    //添加店铺信息
    func requestAddStoreInfo(storeName:String,storeImageUrl:String,storeAddress:String,phone:String,isInstall:String,description:String,content:String,photos:String,storeType:String) -> Void {
        let param =
            ["name":storeName,
             "thumb":storeImageUrl,
             "address":storeAddress,
             "phone":phone,
             "description":description,
             "content":content,
             "hide":isInstall,
             "uid":UserModel.shareUser.data?.uid ?? String(),
             "lat":self.latStr,
             "lng":self.lonStr,
             "province":provinceIdStr,
             "city":cityIdStr,
             "area":townIdStr,
             "joinid":storeType,
             "acceids":photos,
             ] as [String : Any]
        
        Alamofire.request(addStoreDetailsUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        self.customShowSuccess("添加成功", time: 2)
//                        Thread.sleep(forTimeInterval: 0.8)
                self.navigationController?.popToRootViewController(animated: true)
                    
                    case false:
                        self.customShowError(basemodel.msg)
                    }
                    
                case false:
                    self.customShowError("网络请求错误")
                    print(response.result.error!)
                }
                
        }
    }
    
    //获取店铺类型
    func requestGetStoreType() -> Void {
        
        Alamofire.request(getStoreTypeUrl, method:.post, parameters:nil)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = BaseResponseOfArrayModel<StoreTypeModel>()
                    basemodel = BaseResponseOfArrayModel.deserialize(from: response.value)!
                    switch basemodel.status! {
                    case true:
                        self.storeTypeModels = basemodel.data
                        print("数据请求成功")
                    case false:
                        print("数据错误")
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension StoreAddViewController: UITableViewDelegate,UITableViewDataSource,LDImagePickerDelegate,UITextFieldDelegate,ChooseLocationDelegate {
    //        getLonAndLat(address: (textField.text!))
    
//    func textFieldDidEndEditing(_ textField: UITextField) {
//
//        if provinceNameStr == ""||cityNameStr == ""||townNameStr == "" {
//             MBProgressHUD.alertShow(in: self.view, message: "请选择省市区再填写详细地址", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
//            return
//        }
//    getLonAndLat(address:self.provinceNameStr+self.cityNameStr+self.townNameStr + (textField.text!))
//    }
    
    
    func postValueToVc(address: String, lon: String, lat: String) {
        self.latStr = lat
        self.lonStr = lon
    self.footerView?.chooseLocationBtn.setTitle(address, for: UIControlState.normal)
    }
    
    
    func imagePickerDidCancel(_ imagePicker: LDImagePicker!) {
        
    }
    
    func imagePicker(_ imagePicker: LDImagePicker!, didFinished editedImage: UIImage!) {
        let imageData = UIImageJPEGRepresentation(editedImage, 0.00001)
        let formatter = DateFormatter.init()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let str = formatter.string(from:NSDate() as Date) + ".jpg"
        footerView?.TagRunnerImageView.image = editedImage
        if chooseImageType == 0 {
            requestUploadCoverPhoto(imageName: str, imageData: imageData!)
        }else {
            requestUploadCoverPhotos(imageName: str, imageData: imageData!)
        }
        
        
        
    }
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "storeDetailsCell", for: indexPath) as! StoreDetailsTableViewCell
        cell.selectionStyle = .none
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ScaleHeight(40)
    }
    
    //    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    ////      footerView?.TagRunnerImageView.sd_setImage(with: NSURL(string:imageStr)! as URL, placeholderImage: UIImage.init(named: "addImage"))
    //
    //        return self.footerView
    //    }
    //
    //    func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
    //        return 1000
    //    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    
    
}


